package com.jinbiao.quasar.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.db.DbUtil;
import cn.hutool.json.JSONUtil;
import com.jinbiao.quasar.annotate.LoginLog;
import com.jinbiao.quasar.annotate.OperationLog;
import com.jinbiao.quasar.constant.RedisBucketKey;
import com.jinbiao.quasar.dto.*;
import com.jinbiao.quasar.model.SysConfigBackend;
import com.jinbiao.quasar.model.SysConfigFrontend;
import com.jinbiao.quasar.model.SysUser;
import com.jinbiao.quasar.model.SysUserOnline;
import com.jinbiao.quasar.util.AjaxJson;
import com.jinbiao.quasar.util.RedisUtil;
import org.noear.redisx.RedisClient;
import org.noear.redisx.plus.RedisBucket;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.EntityQuery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@Controller
public class LoginController {
    @Db
    SqlToyLazyDao dao;

    @LoginLog
    @Mapping("/public/login")
    public AjaxJson login(LoginDto loginDto){
        String captcha = RedisUtil.getClient().getBucket().get(RedisBucketKey.CAPTCHA +loginDto.getCaptchaId());
        if(!StrUtil.equals(loginDto.getCaptcha(),captcha)) return AjaxJson.getError("验证码错误！");
        List<SysUser> users = dao.findBySql("sysUserList", new SysUser(loginDto.getUsername(), password(loginDto.getPassword())));
        if (users != null && users.size() == 1) {
            SysUser user = users.get(0);
            StpUtil.login(user.getId());
            RedisClient client = RedisUtil.getClient();
            RedisBucket bucket = client.getBucket();
            bucket.store(RedisBucketKey.USER + user.getId(), JSONUtil.toJsonStr(user));
            LoginResultDto loginResultDto = new LoginResultDto();
            BeanUtil.copyProperties(user,loginResultDto,false);
            loginResultDto.setToken(StpUtil.getTokenValue());
            dao.deleteByQuery(SysUserOnline.class,EntityQuery.create().where("username=?").values(user.getUsername()));
            dao.save(new SysUserOnline(user.getUsername(), StpUtil.getTokenValue()));
            return AjaxJson.getSuccess("登录成功",loginResultDto);
        } else if (users != null && users.size() != 1) {
            return AjaxJson.getError("用户数据异常");
        } else {
            return AjaxJson.getError("用户校验失败");
        }
    }

    @Mapping("/public/get-config-backend-all")
    public AjaxJson getConfigBackendAll(){
        return AjaxJson.getSuccessData(dao.findBySql("sysConfigBackendList",new HashMap(), SysConfigBackend.class));
    }
    @Mapping("/public/get-config-frontend-all")
    public AjaxJson getConfigFrontendAll(){
        return AjaxJson.getSuccessData(dao.findBySql("sysConfigFrontendList",new HashMap(), SysConfigFrontend.class));
    }

    @Mapping("/public/check-db")
    public AjaxJson checkDb(){
        String javaVersion = System.getProperty("java.version");
        String jvmVersion = System.getProperty("java.vm.version");
        List<PluginDto> pluginList = new ArrayList<>();
        pluginList.add(new PluginDto("成就系统","plugin-achievement","v0.0.1","这是成就系统插件"));
        pluginList.add(new PluginDto("示例插件","plugin-example","v1.0.0","这是示例插件"));
        List<SysConfigFrontend> frontConfgs =  dao.findBySql("sysConfigFrontendList",new HashMap(), SysConfigFrontend.class);
        Optional<SysConfigFrontend> item = frontConfgs.stream().filter(it->StrUtil.equals(it.getConfigItem(),"pluginLoginLayout")).findFirst();
        String pluginLoginLayout = "";
        if(item.isPresent()) pluginLoginLayout = StrUtil.isNotEmpty(item.get().getItemCustom())?item.get().getItemCustom() : item.get().getItemDefault();
        return AjaxJson.getSuccessData(new CheckDbDto(javaVersion,jvmVersion,pluginLoginLayout,pluginList,false));
    }
    public String password(String password) {
        return MD5.create().digestHex(password);
    }
}
